package com.weh.booksystem.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author weh
 * @create 2023-06-26
 */
public class Interceptor implements HandlerInterceptor {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String servletPath = request.getServletPath();
        System.out.println("______"+ servletPath);

        HttpSession session = request.getSession();
        Object uid = session.getAttribute("uid");
        Object administratorId = session.getAttribute("administratorId");
        System.out.println("administratorId = " + administratorId);
        System.out.println("uid = " + uid);

        // 判断用户是否已登录
        if (uid != null) {
            if(servletPath.equals("/manage.html")
            || servletPath.equals("/managequerybook.html")
            || servletPath.equals("/bookinfomanage.html")
            || servletPath.equals("/usersearch.html")
            || servletPath.equals("/addbook.html")
            || servletPath.equals("/queryuserborrow.html")
            || servletPath.equals("/returnbook.html")){
                response.sendRedirect("/userError.html");
                return false;
            }
            return true; // 用户已登录，继续处理请求
        }
        if (administratorId != null){
            if(servletPath.equals("/mainpage.html")
            || servletPath.equals("/myinfo.html")
            || servletPath.equals("/querybook.html")
            || servletPath.equals("/bookinfo.html")
            || servletPath.equals("/myborrow.html")
            || servletPath.equals("/borrowhistory.html")
            || servletPath.equals("/myreservation.html")){
                response.sendRedirect("administratorError.html");
                return false;
            }
            return true;
        }

        if (servletPath.equals("/index.html")||
                servletPath.equals("/managelogin.html") ||
                servletPath.equals("/register.html")||
                servletPath.equals("/static/assets")||
                servletPath.equals("/static/dist")){
            return true;
        }
        response.sendRedirect("/index.html");
        return false;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("处理前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("处理后");
    }

}
